import 'package:flutter/material.dart';
import 'package:flutter_screenutil/src/size_extension.dart';
import 'package:get/get.dart';

double gap12 = 12.r;
double navBarHeight = 1;

/// 全局悬浮
void dragableItem({
  required VoidCallback onTap,
  required Widget child,
  required double size,
  double? bottom,
}) {
  RxDouble _right = gap12.obs;
  var _bottom = (bottom ?? 120.h).obs;
  var _itemSize = size;

  var _item = OverlayEntry(
    maintainState: true,
    builder: (ctx) {
      return Positioned(
        right: _right.value,
        bottom: _bottom.value,
        // width: _itemSize,
        // height: _height.value,
        child: GestureDetector(
          onTap: onTap,
          child: Draggable(
            feedback: child,
            child: child,
            onDragUpdate: (details) {
              var _maxX = _right.value;
              var _maxY = _bottom.value;

              _maxX -= details.delta.dx;
              _maxY -= details.delta.dy;
              if (_maxX < gap12) {
                _maxX = gap12;
              }
              if (_maxX > Get.width - gap12 - _itemSize) {
                _maxX = Get.width - gap12 - _itemSize;
              }
              if (_maxY <= Get.bottomBarHeight) {
                _maxY = Get.bottomBarHeight;
              }
              if (_maxY >= Get.height - navBarHeight - _itemSize) {
                _maxY = Get.height - navBarHeight - _itemSize;
              }
              _right.value = _maxX;
              _bottom.value = _maxY;
            },
            onDragEnd: (details) {
              if (_right.value < gap12) {
                _right.value = gap12;
              }
              if (_right.value < (Get.width - _itemSize) / 2) {
                _right.value = gap12;
              } else {
                _right.value = Get.width - gap12 - _itemSize;
              }
              if (_bottom.value < Get.bottomBarHeight) {
                _bottom.value = Get.bottomBarHeight;
              }
              if (_bottom.value >= Get.height - navBarHeight - _itemSize) {
                _bottom.value = Get.height - navBarHeight - _itemSize;
              }
            },
          ),
        ),
      );
    },
  );
  Overlay.of(Get.context!)?.insert(_item);
}
